package com.mark.springsecurity.dto.req;

import com.mark.springsecurity.domain.SysUser;
import com.mark.springsecurity.dto.req.vo.SysRoleVo;
import lombok.Data;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.validation.constraints.NotBlank;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

@Data
public class SysUserCmd {

    @NotBlank
    private String realName;
    @NotBlank
    private String username;
    @NotBlank
    private String password;
    @NotBlank
    private String role;

    private Set<SysRoleVo> roleVos = Collections.emptySet();

    public static SysUser buildSysUser(Long id, SysUserCmd sysUserCmd) {
        return SysUser.builder()
                .id(id)
                .role(sysUserCmd.getRole())
                .realName(sysUserCmd.getRealName())
                .username(sysUserCmd.getUsername())
                .password(passwordEncode(sysUserCmd.getPassword()))
                .roles(sysUserCmd.getRoleVos().stream().map(SysRoleVo::buildSysRole).collect(Collectors.toSet()))
                .build();
    }

    public SysUser buildSysUser(SysUserCmd sysUserCmd) {
        return SysUser.builder().realName(sysUserCmd.getRealName())
                .username(sysUserCmd.getUsername())
                .password(passwordEncode(sysUserCmd.getPassword()))
                .role(sysUserCmd.getRole())
                .enabled(Boolean.TRUE)
                .roles(sysUserCmd.getRoleVos().stream().map(SysRoleVo::buildSysRole).collect(Collectors.toSet()))
                .build();
    }

    public static String passwordEncode(String password) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }
}
